package xyz.suancaiyu.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import xyz.suancaiyu.pojo.Book;

import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * 数据库操作.
 *
 * @author puruidong
 * @version 2017/10/21 1.0
 */
@Repository
public class BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 保存数据.
     *
     * @param todo 要增加的项目名称.
     */
    public void save(String todo) {
        jdbcTemplate.update("INSERT INTO Book(id,todo,createdate) VALUES(?,?,?)", new Object[]{UUID.randomUUID(), todo, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))});
    }


    /**
     * 项目列表
     *
     * @return 数据列表.
     */
    public List<Book> list() {
        return jdbcTemplate.query(" select id,todo,createdate from Book ", (RowMapper) (ResultSet resultSet, int i) -> {
            Book book = new Book(resultSet.getString("id"), resultSet.getString("todo"), resultSet.getString("createdate"));
            return book;
        });
    }

    /**
     * 删除数据.
     *
     * @param id
     * @return
     */
    public int delete(String id) {
        return jdbcTemplate.update(" delete from Book where id=? ", id);
    }


}
